define([
    'text!../tpl/adjustBudget.html',
    '../../../framework/bean/admanage',
        '../../../framework/bean/admarket'
        ],
    function(tpl,admanageModel,admarketModel){
    function me(){
        var self = this;
        this.downBudgetReasons = [{id : "ROI_LOW", text : I18N.getText('adOptimize', 'ROI_LOW')},{id : "ROI_WAVE_HEAVILY", text : I18N.getText('adOptimize', 'roiFluctuation')},
            {id : "CPS_HIGH", text :  I18N.getText('adOptimize', 'CPS_HIGH')},{id : "CR_LOW", text : I18N.getText('adOptimize', 'CR_LOW')},
            {id : "CPC_HIGH", text : I18N.getText('adOptimize', 'CPC_HIGH')},
            {id : "CUSTOM_REQUEST", text : I18N.getText('adOptimize', 'CustomeRequirements')}]
        this.upBudgetReasons = [{id : "ROI_HIGH", text : I18N.getText('adOptimize', 'ROI_HIGH')},{id : "CONTINUAL_ROI_HIGH", text : I18N.getText('adOptimize', 'continuousHighROI')},
            {id : "CPS_LOW", text : I18N.getText('adOptimize', 'CPS_LOW')},{id : "CR_HIGH", text : I18N.getText('adOptimize', 'CR_HIGH')},
            {id : "CPC_LOW", text : I18N.getText('adOptimize', 'CPC_LOW')},
            {id : "CUSTOM_REQUEST", text : I18N.getText('adOptimize', 'CustomeRequirements')}]
        this.init = function(adSetId, adId, adMarketTargetId, callback) {
            self.adSetId = adSetId;
            self.adId = adId;
            self.adMarketTargetId = adMarketTargetId;
            self.callback = callback;
            self.render();
        }

        this.render = function(){
            //渲染侧边弹出框
            if (!$('#adjustBudgetPanel')[0]) {
                $('body').append('<div id="adjustBudgetPanel"></div>');
            }
            self.$el = $('#adjustBudgetPanel');
            var params = {
                adSet_id: self.adSetId
            }
            admanageModel.getAdSet(params, function(result) {
                //渲染侧边弹出框
                self.$el.sidepanel({
                    saveBtn: I18N.getText('management', 'saveAndClose'),
                    cancelBtn: I18N.getText('management', 'cancel'),
                    title: I18N.getText('adOptimize', 'adjustBudget'),
                    content: I18N.parse(tpl, window.pageName),
                    callback: self.updateCallback
                });

                var objective = result.adSet && result.adSet.campaign && result.adSet.campaign.objective ? result.adSet.campaign.objective : '';
                self.objective = objective;
                self.targeting_spec = result.targeting_spec;
                result.adSet.promoted_object = result.adSet.promoted_object ? JSON.parse(result.adSet.promoted_object) : {};//把属性的类型从String 转成JSON
                result.adSet.pacing_type = result.adSet.pacing_type ? JSON.parse(result.adSet.pacing_type) : [];
                self.adSet = result.adSet;
                self.initDom();
            })

        }

        this.initDom = function(){
            self.fillAdset(self.adSet);
            self.initAdjustReasonDialog();
        }

        this.initAdjustReasonDialog = function(){
            var _modal = $("#adjustbudget-dialog");
            _modal.modal({
                backdrop: 'static',
                keyboard: false,
                show:false
            });

            _modal.off("show.bs.modal").on("show.bs.modal", function(){
                //UP_BUDGET DOWN_BUDGET
                var reasons;
                var _c;
                if (self.updateParam.optimizingType == "UP_BUDGET"){
                    reasons = self.upBudgetReasons;
                    _c = I18N.getText("adOptimize", "confrimUpBudget", [(Number(self.updateParam.dailyBudget/100).toFixed(2))]);
                } else {
                    reasons = self.downBudgetReasons;
                    _c = I18N.getText("adOptimize", "confrimDownBudget", [(Number(self.updateParam.dailyBudget/100).toFixed(2))]);
                }

                $(".confirm-content", _modal).html(_c);
                $("select[name='adjust-reason-drop']",_modal).empty().select2({
                    data : reasons,
                    placeholder : I18N.getText("adOptimize", "adjustReasons"),
                    multiple:true,
                    allowClear:false,
                    width:'100%'
                })
                $(".adjust-remainder", _modal).hide();
            })

            //取消
            $(".cancel-btn", _modal).off("click").on("click", function(){
                _modal.modal("hide");
            })
            //确定
            $(".ok-btn", _modal).off("click").on("click", function(){
                var reasons = $("select[name='adjust-reason-drop']",_modal).val();
                if (!reasons || reasons.length == 0){
                    $(".adjust-remainder",_modal).show();
                    return;
                }
                self.updateParam.attributions = reasons;
                _modal.modal("hide");
                admarketModel.optimizeAd(self.updateParam, function(result) {
                    self.callback(result.jobId, self.queryStatusOK, self.queryStatusFail); //调用 查询job
                });
            })
        }

        this.updateCallback = function($elem){
            $(".tip").remove();
            //判断预算是否修改
            var _budgetType = $("div.ndp-drop-wrapper[name=budget_type]").data("val");
            if (_budgetType == "lifetime_budget"){
                $elem.sidepanel('hide');
                return;
            }

            if ($("div.ndp-sinput-wrapper[name=budget]").hasClass("error")){
                $(".daily_budget").find("input").focus();
                return;
            }

            var _dB = $("div.ndp-sinput-wrapper[name=budget]").find("input").val();
            if (_dB == ""){
                $(".budget-reminder").html(I18N.getText("adOptimize", "enterBudegt")).removeClass("hide");
                $("div.ndp-sinput-wrapper[name=budget]").addClass("error");
                $(".daily_budget").find("input").focus();
                return;
            }

            var _dBV = Number(Number(_dB) * 100).toFixed(0);
            if (self.adSet.daily_budget && self.adSet.daily_budget == _dBV){
                $elem.sidepanel('hide');
                console.log("未作修改")
                return;
            }


            self.updateParam = {
                adId : self.adId,
                adMarketTargetId : self.adMarketTargetId,
                dailyBudget : _dBV
            }

            var oldBuget = self.adSet.daily_budget ? self.adSet.daily_budget : self.calcDailyBudget(self.adSet.lifetime_budget, self.adSet.start_utc_time, self.adSet.end_utc_time);;
            if (_dBV > oldBuget){
                //DOWN_BUDGET UP_BUDGET
                //预算调高
                self.updateParam.optimizingType = "UP_BUDGET";
            } else {
                //预算调低
                self.updateParam.optimizingType = "DOWN_BUDGET";
            }

            //弹出原因选择框
             $("#adjustbudget-dialog").modal("show");
        }

        this.calcDailyBudget = function(_lifetime_budget, _startDate, _endDate){
            var day = Kit.calculateScheduleDay(_startDate, _endDate);
            var dailyBudget = Number(_lifetime_budget / day).toFixed(0);
            return dailyBudget;
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusOK
         * @param      {<type>}  result  { description }
         */
        this.queryStatusOK = function(result) {
            console.info(result)
            self.$el.sidepanel('hide');
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusFail
         * @param      {<type>}  result  { description }
         */
        this.queryStatusFail = function(result) {
            console.info(result)
        }

        this.buildStrategy = function(targeting_spec){
            console.log(targeting_spec)
            var strategies = [];
            //规则
            self.buildRule(targeting_spec["product_audience_specs"], strategies);
            //版位
            self.buildPageMent(targeting_spec["page_types"], strategies);
            //自定义受众
            self.buildCustomAudience(targeting_spec["custom_audiences"], targeting_spec["excluded_custom_audiences"], strategies);
            //地区
            self.buildLocations(targeting_spec["geo_locations"], targeting_spec["excluded_geo_locations"], strategies);
            //年龄
            self.buildAge(targeting_spec["age_max"], targeting_spec["age_min"], strategies);
            //性别
            self.buildGender(targeting_spec["genders"], strategies);

            if (strategies && strategies.length){
                $(".strategy").html(_.template($('#t-strategies-detail').text())({strategies : strategies}));
            }

        }

        this.buildGender = function(genders, strategies){
            if (genders && genders.length){
                var specs = "";
                var g = genders[0];
                if (1 == g || "1" == g){
                    specs = I18N.getText("adOptimize", "men");
                } else {
                    specs = I18N.getText("adOptimize", "women")
                }

                strategies.push({
                    title : I18N.getText("adOptimize", "gender"),
                    specs : specs
                })
            }
        }

        this.buildAge = function(_max, _min, strategies){
            if (_max && _min){
                var specs = _min + " " + I18N.getText("adOptimize", "to") + " " + _max;
                strategies.push({
                    title : I18N.getText("adOptimize", "age"),
                    specs : specs
                })
            }

        }
        this.buildLocations = function(geo_locations, excluded_geo_locations, strategies){
            if (geo_locations && !Kit.isEmptyObject(geo_locations)){
                var  _initLocationTypes = geo_locations.location_types;
                var title = "";
                if (_initLocationTypes.length > 1){
                    title = I18N.getText("adOptimize", "location");
                } else {
                    if (_initLocationTypes[0] == 'home'){
                        title = I18N.getText("adOptimize", "locationLiving");
                    }

                    if (_initLocationTypes[0] == 'recent'){
                        title = I18N.getText("adOptimize", "locationRecentlyIn");
                    }

                    if (_initLocationTypes[0] == 'travel_in'){
                        title = I18N.getText("adOptimize", "locationTravelingIn");
                    }
                }

                var specs = locations(geo_locations);
                strategies.push({
                    title : title,
                    specs : specs
                })
            }

            if (excluded_geo_locations && !Kit.isEmptyObject(excluded_geo_locations)){
                var specs = locations(excluded_geo_locations);
                strategies.push({
                    title : I18N.getText("adOptimize", "excludeLocation"),
                    specs : specs
                })
            }

            function locations(_locations){
                var s = ""
                //国家
                var countries = _locations["countries"];
                if (countries && countries.length){
                    $.each(countries, function(i, country){
                        if (s != ""){
                            s += ",";
                        }
                        s += country.name;
                    })
                }

                //region
                var regions = _locations["regions"];
                if (regions && regions.length){
                    $.each(regions, function(i, region){
                        if (s != ""){
                            s += ",";
                        }
                        s += region.name;
                    })
                }

                //cities
                var cities = _locations["cities"];
                if (cities && cities.length) {
                    $.each(cities, function(i, city){
                        if (s != ""){
                            s += ",";
                        }
                        s += city.name + '+ ' + city.radius + (city.distance_unit ? city.distance_unit : I18N.getText('management', 'kilometer'));
                    })
                }
                //zip
                var zips = _locations["zips"];
                if (zips && zips.length){
                    $.each(zips, function(i, zip){
                        if (s != ""){
                            s += ",";
                        }
                        s += zip.name;
                    })
                }
                //geo_market
                var geo_markets = _locations["geo_markets"];
                if (geo_markets && geo_markets.length){
                    $.each(geo_markets, function(i, geo_market){
                        if (s != ""){
                            s += ",";
                        }
                        s += geo_market.name  + ',DMA®';
                    })
                }
                //electoral_districts
                var electoral_districts = _locations["electoral_districts"];
                if (electoral_districts && electoral_districts.length){
                    $.each(electoral_districts, function(i, electoral_district){
                        if (s != ""){
                            s += ",";
                        }
                        s += electoral_district.name;
                    })
                }
                //custom_locations
                var custom_locations = _locations["custom_locations"];
                if (custom_locations && custom_locations.length){
                    $.each(custom_locations, function(i, custom_location){
                        if (s != ""){
                            s += ",";
                        }
                        s += '(' +  custom_location.latitude + ',' + custom_location.longitude + ')'
                            +  '+ ' + custom_location.radius +(custom_location.distance_unit ? custom_location.distance_unit : I18N.getText('management', 'kilometer'));
                    })
                }
                return s;
            }

        }

        this.buildCustomAudience = function(custom_audiences, excluded_custom_audiences, strategies){
            if (custom_audiences && custom_audiences.length){
                var specs = "";
                var isFirst = true;
                $.each(custom_audiences, function(i, _custom_audience){
                    if (!isFirst){
                        specs += ",";
                    }
                    specs += _custom_audience.name;
                    isFirst = false;
                })

                strategies.push({
                    title : I18N.getText("adOptimize", "customAudience"),
                    specs : specs
                })
            }

            if (excluded_custom_audiences && excluded_custom_audiences.length){
                var specs = "";
                var isFirst = true;
                $.each(excluded_custom_audiences, function(i, _excluded_custom_audiences){
                    if (!isFirst){
                        specs += ",";
                    }
                    specs += _excluded_custom_audiences.name;
                    isFirst = false;
                })
                strategies.push({
                    title :  I18N.getText("adOptimize", "excludeCustomAudience"),
                    specs : specs
                })
            }
        }

        this.buildPageMent = function(_page_types, strategies){
            if (_page_types && _page_types.length){
                var specs = "";
                var isFirst = true;
                $.each(_page_types, function(i, _page_type){
                    if (!isFirst){
                        specs += ",";
                    }
                    specs += _page_type;
                    isFirst = false;
                })

                strategies.push({
                    title : I18N.getText("adOptimize", "placement"),
                    specs : specs
                })
            }

        }
        this.buildRule = function(_rules, strategies){
            //规则
            var specs = "";
            if (_rules){
                var audience_specs = _rules;
                var sepcs = [];
                $.each(audience_specs, function(i, _audience_spec){
                    var s_sepcs = {};
                    var inclusions = _audience_spec.inclusions;
                    if (inclusions && inclusions.length){
                        $.each(inclusions, function(_i, _inclusion){
                            var _rule = JSON.parse(_inclusion.rule);
                            s_sepcs[_rule.event.eq] = {
                                event : _rule.event.eq,
                                max : Number(_inclusion.retention_seconds / 24 / 60 / 60).toFixed(0)
                            }
                        })
                    }

                    var exclusions = _audience_spec.exclusions;
                    if (exclusions && exclusions.length){
                        $.each(exclusions, function(_i, _exclusion){
                            var _rule = JSON.parse(_exclusion.rule);
                            var s = s_sepcs[_rule.event.eq];
                            if (s){
                                s.min = Number(_exclusion.retention_seconds / 24 / 60 / 60).toFixed(0);
                            } else {
                                s_sepcs[_rule.event.eq] = {
                                    event : _rule.event.eq,
                                    min : Number(_exclusion.retention_seconds / 24 / 60 / 60).toFixed(0)
                                }
                            }
                        })
                    }

                    var spec = I18N.getText('adOptimize', "associatedProductSet") + (_audience_spec.product_set_name ? _audience_spec.product_set_name : _audience_spec.product_set_id) + " : ";
                    var isFirst = true;
                    $.each(s_sepcs, function(_k, _v){
                        if(!isFirst){
                            spec += ";"
                        }
                        spec += I18N.getText('adOptimize', "last");
                        if (_v.min && _v.max){
                            spec += _v.min +  I18N.getText('adOptimize', "to") + _v.max +  I18N.getText('adOptimize', "day")  + " " + Kit.translate('adOptimize', $.trim(_v.event))
                        } else if (_v.max) {
                            spec += _v.max + I18N.getText('adOptimize', "day")  + " " + Kit.translate('adOptimize', $.trim(_v.event));
                        } else {
                            spec += _v.min + I18N.getText('adOptimize', "day")  + " "  + I18N.getText('adOptimize', "not") + Kit.translate('adOptimize', $.trim(_v.event))
                        }
                        isFirst = false;
                    });
                    specs += spec + "</br>";
                    //sepcs.push(spec);
                })
            }
            if ("" != specs){
                strategies.push({
                    title : I18N.getText('adOptimize', "rule"),
                    specs : specs
                })
            }
        }

        this.fillAdset = function(_adset){
            //构造策略、用户定位描述
            self.buildStrategy(self.targeting_spec);

            //排期
            var _startTimeShow = moment(_adset.start_utc_time).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD HH:mm');
            var _endTimeShow = ''
            if (_adset.end_utc_time) {
                _endTimeShow = moment(_adset.end_utc_time).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD HH:mm');
            } else {
                _endTimeShow = I18N.getText('createAd', 'continuously');
            }
            $(".schedule").html(_startTimeShow + ' ~ ' + _endTimeShow);

            //优化方式
            $(".optGoal").html(I18N.getText('adOptimize', _adset.optimization_goal));
            if (_adset.optimization_goal == "OFFSITE_CONVERSIONS" && _adset.promoted_object && _adset.promoted_object.custom_event_type){
                $(".customEventType").html(I18N.getText('adOptimize', _adset.promoted_object.custom_event_type));
            }

            //收费方式
            $(".billingEvent").html(I18N.getText('adOptimize', _adset.billing_event));

            //单价
            var _bidShow;
            if (_adset.bid_amount && !_adset.is_autobid){
                //手动出价
                _bidShow = I18N.getText('adOptimize', "manual") + "    $" + Number(_adset.bid_amount / 100).toFixed(2);
            } else {
                //自动出价
                _bidShow = I18N.getText('adOptimize', "automatic")
            }
            $(".bidAmount").html(_bidShow);

            //投放类型
            var _deliveryType;
            if (!_adset.pacing_type || _adset.pacing_type.length == 0 || _adset.pacing_type.indexOf("standard") > -1){
                //标准
                _deliveryType = "standard";
            } else {
                //加速
                _deliveryType = "accelerated";
            }
            $(".deliveryType").html(I18N.getText('adOptimize', _deliveryType));
            $(".deliveryType-d").html(I18N.getText('adOptimize', _deliveryType + "-label"));

            //预算
            var budgetTypes = [{"val" : "daily_budget", "text" : I18N.getText('adOptimize', "dailyBudget")}];
            // _adset.daily_budget = 0;
            // _adset.lifetime_budget = 3000;
            if (_adset.daily_budget){
                //日预算，可以修改
                $("div.ndp-sinput-wrapper[name=budget]").sinput({
                    xion:"<span>$</span>",
                    placeholder:I18N.getText('createAd', 'pleaseInputBudget'),
                    pos:"left",//图标显示在左边  “left”, "right"
                    default: Number(_adset.daily_budget / 100).toFixed(2)
                });
                $(".lifetime_budget").hide();
            } else if(_adset.lifetime_budget){
                //总预算
                budgetTypes.unshift({"val" : "lifetime_budget", "text" : I18N.getText('adOptimize', "lifetimeBudget")})
                $(".daily_budget").hide();
                $("div.ndp-sinput-wrapper[name=budget]").sinput({
                    xion:"<span>$</span>",
                    placeholder:I18N.getText('createAd', 'pleaseInputBudget'),
                    pos:"left"//图标显示在左边  “left”, "right"
                });
                $(".lifetime_budget").html("$" + Number(_adset.lifetime_budget / 100).toFixed(2)).show()
            }

            //预算值只能精确到小数点后两位
            $("div.ndp-sinput-wrapper[name=budget]").find("input").numeral({ 'scale': 2 });

            //输入预算需要校验
            $("div.ndp-sinput-wrapper[name=budget]").find("input").off('keyup').on('keyup',
                function(e){
                if ($(this).val() == ''){
                    $(".budget-reminder").html("").addClass("hide");
                    $(this).parent().removeClass("error")
                    return;
                }

                var info = {
                    billing_event: _adset.billing_event
                }

                var warning = Kit.validateBudget(info, _adset.bid_amount ? Number(_adset.bid_amount / 100).toFixed(2): 0,
                    $(this).val(),
                    "daily_budget",
                    _adset.start_utc_time, _adset.end_utc_time);

                if (warning){
                    $(".budget-reminder").html(warning).removeClass("hide");
                    $(this).parent().addClass("error")
                } else {
                    $(".budget-reminder").html("").addClass("hide");
                    $(this).parent().removeClass("error");
                }
            });

            //单价
            $(".budget_type").empty().drop({
                data: budgetTypes,
                caret: "glyphicon-menu-right"
            }).off("ITEM_CHANGE").on("ITEM_CHANGE", function(e){
                var _budgetType = e.originalEvent.data.val;
                if (_budgetType == "daily_budget"){
                    $(".daily_budget").show();
                    $(".lifetime_budget").hide();
                } else {
                    $(".daily_budget").hide();
                    $(".lifetime_budget").show();
                }
            }).val(budgetTypes[0])
        }
    }

    return me;
})
